package com.xiangxiangjd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xiangxiangjd.bean.Role;
import com.xiangxiangjd.bean.Unit;
import com.xiangxiangjd.controller.entity.ApiCode;
import com.xiangxiangjd.controller.helper.$;
import com.xiangxiangjd.utils.StringUtilsXiao;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.xiangxiangjd.bean.result.ResultPage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import com.xiangxiangjd.service.TrUserService;
import com.xiangxiangjd.bean.TrUser;
import com.xiangxiangjd.controller.model.ApiResultModel;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 肖守凯
 * @since 2021-06-11
 */
@Controller
@RequestMapping("/api/trUser")
@Api(tags = "用户")
public class TrUserController extends BaseController {


    /**
     * 分页查询TrUser
     *
     * @param page   页码
     * @param limit  查几条
     * @param trUser 前端传进的参数
     * @return 返回统一分页信息
     */
    @PostMapping(value = "admin/findTrUserByPage")
    @ResponseBody
    @ApiOperation(value = "分页查询用户", notes = "分页查询用户", produces = "application/json")
    @PreAuthorize("hasRole('ROLE_USER')")
    public ResultPage findTrUserByPage(Integer page, Integer limit, TrUser trUser) {

        TrUser userInfo = getUserInfo();
        if (userInfo.getUserAdmin().equals("0")) {
            System.out.println("是普通用户");
            trUser.setId(userInfo.getId());
        } else if (userInfo.getUserAdmin().equals("1")) {
            System.out.println("是管理员");
            trUser.setUserAdmin("0");
        }
        return trUserService.findTrUserByPage(page, limit, trUser);
    }



    @PostMapping(value = "/getAllUser")
    @ResponseBody
    @ApiOperation(value = "查询所有的用户", notes = "查询所有的用户", produces = "application/json")
    @PreAuthorize("hasRole('ROLE_USER')")
    public ApiResultModel getAllUser() {


        return $.success(trUserService.list());
    }


    @PostMapping(value = "/getAllUserNoMy")
    @ResponseBody
    @ApiOperation(value = "查询系统用户（排除自己）", notes = "查询系统用户（排除自己）", produces = "application/json")
    @PreAuthorize("hasRole('ROLE_USER')")
    public ApiResultModel getAllUserNoMy() {

        List<TrUser> listUser = trUserService.list(new LambdaQueryWrapper<TrUser>().ne(TrUser::getId, getUserInfo().getId()));

        return $.success(listUser);
    }


    // 用户的权限
    private static final Map<Integer, String> PURVIEW = new HashMap();


    //允许上传的格式
    static {
        PURVIEW.put(0, "user");
        PURVIEW.put(1, "admin");
        PURVIEW.put(2, "super");
    }


    /**
     * 添加TrUser
     *
     * @param trUser 前端传进的参数
     * @return 返回统一信息
     */
    @PostMapping(value = "admin/addTrUser")
    @ResponseBody
    @ApiOperation(value = "添加用户", notes = "添加用户", produces = "application/json")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ApiResultModel saveTrUser(TrUser trUser) {

        //获取当前用户的信息 权限
        String userAdmin = getUserInfo().getUserAdmin();

        switch (userAdmin) {
            case "0":
                return $.error("权限不住 禁止添加用户");
            case "1":
                if (trUser.getUserAdmin().equals(2)) {
                    return $.error("权限不住 禁止添加用户");
                }
                break;
            default:

        }

        List<TrUser> list = trUserService.list(new LambdaQueryWrapper<TrUser>().eq(TrUser::getUserName, trUser.getUserName()));
        if (list.size() > 0) return $.error("用户名已经存在");

        if (StringUtilsXiao.isBlank(trUser.getPassWord())) {
            return $.error("密码不可为空");
        }

        //判断角色是否存在
        if (roleService.getById(trUser.getRoleId()) == null) return $.error("添加的角色不存在！");

        return trUserService.addTrUser(trUser);
    }

    /**
     * 编辑TrUser
     *
     * @param trUser 前端传进的参数
     * @return 返回统一信息
     */
    @PostMapping(value = "admin/editTrUser")
    @ResponseBody
    @ApiOperation(value = "编辑用户", notes = "编辑用户")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ApiResultModel editTrUser(TrUser trUser) {
        System.out.println(trUser.toString());
        return trUserService.editTrUser(trUser);
    }

    /**
     * 删除TrUser
     *
     * @param ids 前端传进的ID
     * @return 返回统一信息
     */
    @PostMapping(value = "admin/delTrUser")
    @ResponseBody
    @ApiOperation(value = "删除用户", notes = "删除用户")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ApiResultModel delTrUser(@RequestParam("datas") ArrayList ids) {

        ids.forEach(a -> System.out.println(a));


        return trUserService.delTrUsers(ids);
    }


    //更具token 获取用户信息
    @GetMapping(value = "/getUser")
    @ResponseBody
    @ApiOperation(value = "获取用户信息", notes = "获取用户信息")
    @PreAuthorize("hasRole('ROLE_USER')")
    public ResultPage getUser() {
        String tokenHead = "Bearer ";
        HttpServletRequest request = getRequest();
        String token = request.getHeader("Authorization");
        Claims claims = jwtUtils.parseJwt(token.substring(tokenHead.length()));
        String username = claims.getId();
        TrUser user = trUserService.getUser(username);
        //获取单位所有的上级
        List<Unit> unitFatherAll = unitService.getFatherAll(user.getUnitId());
        user.setFatherUnitAll(unitFatherAll);
        ArrayList<TrUser> trUsers = new ArrayList<>();
        trUsers.add(user);
        ResultPage data = new ResultPage();
        data.setCount(trUsers.size());
        data.setMsg(ApiCode.success_msg);
        data.setCode(200);
        data.setData(trUsers);
        return data;
    }


    @GetMapping(value = "/getByUser")
    @ResponseBody
    @ApiOperation(value = "回显用户信息", notes = "回显用户信息")
    @PreAuthorize("hasRole('ROLE_USER')")
    public Object getByUser(String username) throws Exception {

        System.out.println(username);

        //获取当前用户的 角色id
        TrUser user = trUserService.getUser(username);

        if (user == null) {
            return $.error("用户不存在");
        }

        System.out.println(user.toString());

        String roleId = user.getRoleId();

        //获取用户角色所有的上级
        List<Role> fatherAll = roleService.getFatherAll(roleId);
        user.setFatherRoleAll(fatherAll);

        //获取单位所有的上级
        List<Unit> unitFatherAll = unitService.getFatherAll(user.getUnitId());
        user.setFatherUnitAll(unitFatherAll);


        ArrayList<TrUser> trUsers = new ArrayList<>();
        trUsers.add(user);
        ResultPage data = new ResultPage();
        data.setCount(trUsers.size());
        data.setMsg(ApiCode.success_msg);
        data.setCode(200);
        data.setData(trUsers);
        return data;
    }





    /**
     *
     *  修改密码
     * @param ids 前端传进的ID
     * @return 返回统一信息
     */
    @PostMapping(value = "/updatePassword")
    @ResponseBody
    @ApiOperation(value = "修改密码", notes = "修改密码")
    @PreAuthorize("hasRole('ROLE_USER')")
    public ApiResultModel updatePassword(@RequestParam("id") String id,@RequestParam("newPassword") String newPassword) {

        boolean update = trUserService.update(new LambdaUpdateWrapper<TrUser>().set(TrUser::getPassWord, newPassword).eq(TrUser::getId, id));
        if(!update){return  $.error("修改密码失败");}

        return $.success("修改密码成功");
    }

    @PostMapping(value = "/trUser")
    @ResponseBody
    public ResultPage findTrUserByPage(@RequestBody TrUser trUser) {

        return null;
    }



}
